package com.zrrd.gmall.product.controller;

import com.zrrd.gmall.common.result.Result;
import jodd.io.FileNameUtil;
import lombok.extern.slf4j.Slf4j;
import org.csource.common.MyException;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
@Slf4j
@RestController
@RequestMapping("/admin/product")
public class FileUploadController {
    @Value("${fileServer.url}")
    private String fileUrl;
    @PostMapping("/fileUpload")
    public Result<String> fileUpload(MultipartFile file) throws MyException, IOException {
        String path ="";
        //1.加载配置文件
        String configFile = this.getClass().getResource("/tracker.conf").getFile();
        //2.非空判断
        if (configFile!=null){
            ClientGlobal.init(configFile);
            TrackerClient trackerClient = new TrackerClient();
            //5.得到上传连接对象
            TrackerServer trackerServer = trackerClient.getConnection();
            StorageClient1 storageClient1 =new StorageClient1(trackerServer,null);
            //                                       文件字节数组                         文件后缀                             额外选项
            path = storageClient1.upload_appender_file1(file.getBytes(), FileNameUtil.getExtension(file.getOriginalFilename()), null);
        }else {
            return Result.fail("初始化失败");
        }
        log.info("文件上传成功");
        return Result.ok(fileUrl+path);
    }
}
